﻿using System;
using System.Linq;
using RrslLite.Configuration;

namespace RrslLite
{
    public class BatchFuncCall<TResult> : BatchCall
    {
        private readonly Action<TResult> _handler;

        protected BatchBuilderConfiguration BatchBuilderConfiguration
        {
            get { return RrslLiteConfiguration.Instance.BatchBuilderConfiguration; }
        }

        public BatchFuncCall(Action<BatchCall> call, Action<TResult> handler) : base(call)
        {
            _handler = handler;
        }

        public override void Callback(object data)
        {
            TResult result = default(TResult);

            if (data is TResult)
            {
                result = AttachInterceptorsAndCreateProxy(data);
            }

            _handler(result);
        }

        protected TResult AttachInterceptorsAndCreateProxy(object data)
        {
            return (TResult) BatchBuilderConfiguration
                                 .ReceiveProxyGeneratorMethod
                                     (data,
                                      BatchBuilderConfiguration.EntityAopProxyGeneratorConfiguration.ProxyGenerationOptionsFunc(),
                                      BatchBuilderConfiguration.EntityAopProxyGeneratorConfiguration.MessageReceiveInterceptors.ToArray());
        }
    }
}